package com.mission.shaco.warehouse;

/**
 * Created by Shaco on 2017/6/16.
 */


import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;

import com.smartdevice.aidl.ICallBack;
import com.mission.shaco.warehouse.models.ClientConfig;
import com.mission.shaco.warehouse.models.util.ExecutorFactory;

import java.util.ArrayList;

import static com.mission.shaco.warehouse.models.ClientConfig.CHECK_TIME_SPACE;

@TargetApi(Build.VERSION_CODES.CUPCAKE)
public class ScannerActivity extends BaseActivity implements OnClickListener {


    public  static final int SCAN_STATUS_OPEN = 0;
    public  static final int SCAN_STATUS_RECEIVE = 1;
    public  static final int SCAN_STATUS_SEND = 2;
    public  static long lastGetCodeTime = 0;
    public String batchNumber = "";

    public String[] errorList = {"不做操作","靠后配","库存不足", "条码异常", "产品损坏"};

    protected boolean runFlag = true;
    public String text = "";
    public String code = "";
    protected RemoteControlReceiver screenStatusReceiver = null;
    protected MediaPlayer player;
    protected Vibrator vibrator;
    protected String firstCodeStr = "";
    protected boolean beginToReceiverData = true;
    protected int send = 0,receiver=0;



    protected ICallBack.Stub mCallback = new ICallBack.Stub() {
        @Override
        public void onReturnValue(byte[] buffer, int size)
                throws RemoteException {

            code = "";

            if(beginToReceiverData&&DEVICE_MODEL==3505){
                beginToReceiverData = false;
                return;
            }
            String codeStr = new String(buffer);

            if( codeStr.indexOf("{") > -1 ){
                code = codeStr.substring(0,codeStr.indexOf("{"));
            }


            if(ClientConfig.getBoolean(ClientConfig.SCAN_REPEAT)){
                if(firstCodeStr.equals(codeStr)){
                    vibrator.vibrate(100);
                }
            }
            if(ClientConfig.getBoolean(ClientConfig.APPEND_RINGTONE)){
                player.start();
            }
            if(ClientConfig.getBoolean(ClientConfig.APPEND_VIBRATE)){
                vibrator.vibrate(100);
            }
            firstCodeStr = codeStr;

            codeStr="";

            //发送到外部接收
            //Intent intentBroadcast = new Intent();
            //intentBroadcast.setAction("com.zkc.scancode");
            //intentBroadcast.putExtra("code", code);
            //sendBroadcast(intentBroadcast);

            text += codeStr;

            int startIndex = text.indexOf("{");
            int endIndex = text.indexOf("}");



            String keyStr = "";
            if (startIndex > -1 && endIndex > -1 && endIndex - startIndex < 5) {
                keyStr = text.substring(startIndex + 1, endIndex);
                text = text.substring(0, text.indexOf("{"));
                lastGetCodeTime = System.currentTimeMillis();
            }

            text="";

//            if (!keyStr.equals("")) {
//                text += "\r\n";
//            }

            if(!TextUtils.isEmpty(code)){
                mHandler.sendEmptyMessage(SCAN_STATUS_RECEIVE);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();

        // 媒体播放服务
        player = MediaPlayer.create(getApplicationContext(), R.raw.beep);

        // 手机震动服务
        vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

        // 屏幕状态接收器
        screenStatusReceiver = new RemoteControlReceiver();

        IntentFilter screenStatusIF = new IntentFilter();
        screenStatusIF.addAction(Intent.ACTION_SCREEN_ON);
        screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF);
        screenStatusIF.addAction(Intent.ACTION_SHUTDOWN);
        screenStatusIF.addAction("com.zkc.keycode");
        registerReceiver(screenStatusReceiver, screenStatusIF);

        ExecutorFactory.executeThread(new Runnable() {

            @Override
            public void run() {
                while (runFlag) {
                    if (bindSuccessFlag) {
                        // 注册回调接口
                        try {

                            mIzkcService.registerCallBack("Scanner", mCallback);
                            // 关闭线程
                            runFlag = false;
                            mHandler.sendEmptyMessage(SCAN_STATUS_SEND);
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            runFlag = false;
                            e.printStackTrace();
                        }
                    }
                }

            }
        });
    }

    protected Boolean checkLastTime(){
        Long now = System.currentTimeMillis();
        Long min =  now - lastGetCodeTime;
        if(min > CHECK_TIME_SPACE){
            return true;
        }else{
            return false;
        }
    }

    public void saveRunState(){}

    protected void afterScanSet(){

    }

    protected Boolean isCurrentClass(){
        String current = this.getClass().toString();
        if(current.equals(currentScanClass)){
            return true;
        }else{
            return false;
        }
    }

    protected void beforeScanSet(){}

    protected void afterScanReceive(){
        code="";
    }

    public void complete(){}

    protected void afterScanOpen(){}


    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case SCAN_STATUS_OPEN:
                    beforeScanSet();
                    initScanSet();
                    afterScanSet();
                    break;
                case SCAN_STATUS_RECEIVE:
                    afterScanReceive();
                    break;
                case SCAN_STATUS_SEND:
                    afterScanOpen();
                    break;
                default:
                    break;
            }
            return false;
        }
    });



    @Override
    protected void onResume() {
        initScanSet();
        super.onResume();
    }

    private void initView() {


    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            default:
                break;
        }

        if (intent != null)
            startActivity(intent);

    }

    void initScanSet(){

        if(mIzkcService!=null){
            try {
                mIzkcService.openScan(ClientConfig.getBoolean(ClientConfig.OPEN_SCAN));
 //               mIzkcService.dataAppendEnter(false);
//				mIzkcService.appendRingTone(ClientConfig.getBoolean(ClientConfig.APPEND_RINGTONE));
                mIzkcService.continueScan(false);
//				mIzkcService.scanRepeatHint(ClientConfig.getBoolean(ClientConfig.SCAN_REPEAT));
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 135:

                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    //3503不需要注册改广播
    int count = 0;
    public class RemoteControlReceiver extends BroadcastReceiver {

        private static final String TAG = "RemoteControlReceiver";
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            beginToReceiverData = false;
            Log.i(TAG, "System message " + action);
            if(action.equals("com.zkc.keycode")) {
                if(count++>0){
                    count = 0;
                    int keyValue = intent.getIntExtra("keyvalue", 0);
                    Log.i(TAG, "KEY VALUE:"+keyValue);
                    if (keyValue == 136 || keyValue == 135 || keyValue == 131) {
                        Log.i(TAG, "Scan key down.........");
                        try {
                            if(mIzkcService!=null)
                                mIzkcService.scan();
                            mHandler.sendEmptyMessage(SCAN_STATUS_RECEIVE);
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            } else if (action.equals("android.intent.action.SCREEN_ON")) {
                Log.i(TAG, "Power off,Close scan modules power.........");
                if(mIzkcService!=null)
                    initScanSet();
            } else if (action.equals("android.intent.action.SCREEN_OFF")) {
                Log.i(TAG, "ACTION_SCREEN_OFF,Close scan modules power.........");
                try {
                    if(mIzkcService!=null)
                        mIzkcService.openScan(false);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (action.equals("android.intent.action.ACTION_SHUTDOWN")) {
                Log.i(TAG, "ACTION_SCREEN_ON,Open scan modules power.........");
                try {
                    if(mIzkcService!=null)
                        mIzkcService.openScan(false);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(screenStatusReceiver);
        super.onDestroy();
    }

    public void resetCompleteQty(){
        //to son class overwrite
    }

}
